package com.bocai.yuweiwangluo.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bocai.yuweiwangluo.R;
import com.bocai.yuweiwangluo.View.RoundImageView;
import com.bocai.yuweiwangluo.base.BaseActivity;
import com.bocai.yuweiwangluo.bean.PopBean;
import com.bocai.yuweiwangluo.bean.TypesBean;
import com.bocai.yuweiwangluo.pickaddress.ChangeAddressDialog;
import com.bocai.yuweiwangluo.presenter.PersonInfoPresenter;
import com.bocai.yuweiwangluo.utils.MyConst;
import com.bocai.yuweiwangluo.utils.PopUtil;
import com.bocai.yuweiwangluo.utils.SharePrefencesUtil;
import com.bocai.yuweiwangluo.viewModel.IPersonInfoView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wq.photo.MediaChoseActivity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 个人信息
 */
public class PersonalInformationActivity extends BaseActivity implements View.OnClickListener,IPersonInfoView
{
    @ViewInject(R.id.ll_change_photo)
    LinearLayout ll_change_photo;
    @ViewInject(R.id.ll_setting_sex)
    LinearLayout ll_setting_sex;
    @ViewInject(R.id.riv_photo)
    RoundImageView riv_photo;
    @ViewInject(R.id.tv_sex)
    TextView tv_sex;
    @ViewInject(R.id.btn_personinfo_exit)
    Button btnExit;
    @ViewInject(R.id.ll_personinfo_name)
    LinearLayout llNickName;
    @ViewInject(R.id.tv_personinfo_name)
    TextView tvNickName;
    @ViewInject(R.id.ll_personinfo_area)
    LinearLayout llarea;
    @ViewInject(R.id.tv_personinfo_area)
    TextView tvarea;
    @ViewInject(R.id.ll_personinfo_sport)
    LinearLayout llSport;
    @ViewInject(R.id.tv_personinfo_sport)
    TextView tvSport;
    private String nickname="";
    PersonInfoPresenter personInfoPresenter;
    ArrayList<String> paths;
    private String photo;
    private TypesBean typesBean=new TypesBean();
    private ArrayList<PopBean> list;
    private PopUtil pu;
    private int width;
    String typeId;
    @Override
    protected int contentView()
    {
        return R.layout.activity_personal_information;
    }

    @Override
    protected void setData()
    {
        WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        width=windowManager.getDefaultDisplay().getWidth();
        typesBean= (TypesBean) getIntent().getSerializableExtra("types");
        SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_PRIVATE);
        String id=sharedPreferences.getString("user_id","-1");
        MyConst.user_id=id;
        ViewUtils.inject(this);
        initToolbar("个人信息");
        getPersonInfoPresenter();
        getUserInfo();
        initEvent();
    }

    private void getUserInfo() {
        personInfoPresenter.getUserInfo();
    }

    @Override
    protected void initEvent()
    {
        super.initEvent();
        ll_setting_sex.setOnClickListener(this);
        ll_change_photo.setOnClickListener(this);
        btnExit.setOnClickListener(this);
        llNickName.setOnClickListener(this);
        llarea.setOnClickListener(this);
        llSport.setOnClickListener(this);
    }
    private void showPopwindow(View v,final TextView tv,ArrayList<PopBean> list,final int what,int width,int height)
    {
        try{

            pu= PopUtil.getInstance(this, v, width, height, list);
            pu.setListener(new PopUtil.OnDatePopClickListener()
            {
                @Override
                public void onClick(PopUtil pu, PopBean date)
                {
                    try{
                        tv.setText(date.getName());
                        pu.dismiss();
                        if(0==what)//运动类型
                        {
                            typeId = date.getId();
                            tvSport.setText(date.getName());
                            personInfoPresenter.updataInfo(tv_sex.getText().toString(),tvarea.getText().toString(),typeId);
                        }
                    }catch (Exception e){}
                }
            });
            pu.show();
        }catch (Exception e){}
    }

    //设置运动类型数据
    private ArrayList<PopBean> setTypeList() {
        try
        {

            list=new ArrayList<>();
            if(typesBean!=null){

                for (int i=0;i<typesBean.getType().size();i++)
                {
                    PopBean popBean=new PopBean();
                        popBean.setId(typesBean.getType().get(i).getId());
                        popBean.setName(typesBean.getType().get(i).getTitle());
                    list.add(i,popBean);
                }
            }
        }catch (Exception e){}
        return list;
    }
    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ll_personinfo_sport:
                if(typesBean.getType()!=null) {
                    showPopwindow(v, tvSport, setTypeList(), 0,width,width/2);
                }
                break;
            case R.id.ll_personinfo_area:
                ChangeAddressDialog mChangeAddressDialog = new ChangeAddressDialog(
                        this);
                mChangeAddressDialog.setAddress("浙江", "杭州");
                mChangeAddressDialog.show();
                mChangeAddressDialog
                        .setAddresskListener(new ChangeAddressDialog.OnAddressCListener() {

                            @Override
                            public void onClick(String province, String city) {
                                // TODO Auto-generated method stub
//                                Toast.makeText(PersonalInformationActivity.this,
//                                        province + "-" + city,
//                                        Toast.LENGTH_LONG).show();
                                personInfoPresenter.updataInfo(tv_sex.getText().toString(),province + " "+city,typeId);
                                tvarea.setText(province + " " + city);
                            }
                        });
                break;
            case R.id.ll_personinfo_name:
                Intent intent1=new Intent(this,UpdataNickNameActivity.class);
                intent1.putExtra("nickname",tvNickName.getText().toString());
                this.startActivityForResult(intent1,2000);
                break;
            case R.id.ll_setting_sex:
                View view = LayoutInflater.from(this).inflate(R.layout.dialog_selector_sex, null);
                final AlertDialog dialog = new AlertDialog.Builder(this)
                        .setView(view)
                        .show();
                view.findViewById(R.id.man).setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        tv_sex.setText("男");
                        dialog.cancel();
                        personInfoPresenter.updataInfo("男", tvarea.getText().toString(),typeId);

                    }
                });
                view.findViewById(R.id.woman).setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        tv_sex.setText("女");
                        dialog.cancel();
                        personInfoPresenter.updataInfo("女",tvarea.getText().toString(),typeId);
                    }
                });
                break;
            case R.id.ll_change_photo:
                Intent intent = new Intent(this, MediaChoseActivity.class);
                intent.putExtra("chose_mode", 0);
                intent.putExtra("crop", true);
                startActivityForResult(intent, 1000);
                break;
            case R.id.btn_personinfo_exit:
                SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_PRIVATE);
                SharedPreferences.Editor editor=sharedPreferences.edit();
                if(!"true".equals(SharePrefencesUtil.getIsRememberPsd(this)))
                {
                    editor.putString("password","");
                }
                editor.putString("user_id","");
                editor.putString("nickname","");
                editor.putString("flag","");
                editor.putString("state", "");
                editor.putString("number", "");
                editor.putString("photo","");
                editor.commit();
                startActivity(new Intent(this,LoginActivity.class));
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1000:
                if (resultCode == RESULT_OK)
                {
                    paths = data.getStringArrayListExtra("data");
                    Log.i("cxfs", paths + "");
                    if (data != null)
                    {
                        showLoading();
                        new MyAsyncTask().execute();
                    }
                }

                break;
            case 2000:
                if(data!=null){
                    nickname= data.getStringExtra("nickname");
                    tvNickName.setText(nickname);
                }
                break;
        }
    }
    /**
     * 生成该类的对象，并调用execute方法之后
     * 首先执行的是onProExecute方法
     * 其次执行doInBackgroup方法
     *
     */
     class MyAsyncTask extends AsyncTask<Integer, Integer, String> {


        public MyAsyncTask() {
            super();
        }


        /**
         * 这里的Integer参数对应AsyncTask中的第一个参数
         * 这里的String返回值对应AsyncTask的第三个参数
         * 该方法并不运行在UI线程当中，主要用于异步操作，所有在该方法中不能对UI当中的空间进行设置和修改
         * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作
         */
        @Override
        protected String doInBackground(Integer... params) {
            Bitmap bitmap = BitmapFactory.decodeFile(paths.get(0));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 30, baos);
            try
            {
                baos.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            byte[] buffer = baos.toByteArray();
            photo = Base64.encodeToString(buffer, 0, buffer.length, Base64.DEFAULT);
            return photo;
        }
        /**
         * 这里的String参数对应AsyncTask中的第三个参数（也就是接收doInBackground的返回值）
         * 在doInBackground方法执行结束之后在运行，并且运行在UI线程当中 可以对UI空间进行设置
         */
        @Override
        protected void onPostExecute(String result) {
            personInfoPresenter.upLoadPhoto(photo, "jpg");
        }
    }
    @Override
    public PersonInfoPresenter getPersonInfoPresenter() {
        personInfoPresenter=new PersonInfoPresenter(this,this,this);
        return personInfoPresenter;
    }

    @Override
    public RoundImageView getPhotoView() {
        return riv_photo;
    }

    @Override
    public TextView getNickNameTv() {
        return tvNickName;
    }

    @Override
    public TextView getSexTv() {
        return tv_sex;
    }

    @Override
    public TextView getAreaTv() {
        return tvarea;
    }

    @Override
    public TextView getSportType() {
        return tvSport;
    }

    @Override
    public void setTypeId(String typeId) {
        this.typeId=typeId;
    }

    @Override
    public void photoSucceseCallBack() {
        riv_photo.setImageBitmap(BitmapFactory.decodeFile(paths.get(0)));
    }


    @Override
    public void finishActivity() {
        Intent intent=new Intent();
        String photoPath=personInfoPresenter.getPhotoPath();
        intent.putExtra("photo",photoPath);
        intent.putExtra("nickname",nickname);
        setResult(-1, intent);
        this.finish();


    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            finishActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
